import json, xlrd, os, logging
from django.conf import settings
from django.shortcuts import render
from django.http import HttpResponse
from excel_upload.models import Staff, Organization

logging.basicConfig(filename='server.log', format="%(asctime)s - %(message)s", level=logging.DEBUG)


# Create your views here.
class ExcelUploadView(object):
    def render_temp(self, request, *args, **kwargs):
        # 渲染上传文件HTML
        return render(request=request, template_name='excel_upload.html')

    def valid_file(self, request):
        '''
        验证传入文件是否为Excel，如果是则写入upload文件夹下，如果不是则删除
        :param request:
        :return:
        '''
        try:
            result = {}
            upload_files = request.FILES.getlist('myfile')[0]
            folder_path = os.path.join(settings.BASE_DIR, 'upload')
            if not os.path.exists(folder_path):
                os.makedirs(folder_path)
            file_path = os.path.join(folder_path, upload_files.name)

            f_read = open(file_path, 'wb')
            for chrunk in upload_files.chunks():
                f_read.write(chrunk)
            f_read.close()
            excel_con = None
            try:
                excel_con = xlrd.open_workbook(file_path)
            except:
                os.remove(file_path)
                result['is_sucess'] = False
                result['info'] = '此文件不是Excel！'
                return HttpResponse(json.dumps(result), content_type="application/json")

            analysis_res = None
            if excel_con:
                analysis_res = self.analysis_flied(excel_con)
                result = analysis_res
            return HttpResponse(json.dumps(result), content_type="application/json")
        except Exception as e:
            result = {
                'is_sucess': False,
                'info': e.args[0],
            }
            return HttpResponse(json.dumps(result), content_type="application/json")

    def analysis_flied(self, excel_con):
        # 分析字段插入表中
        # 此函数可以移植到celery中执行，或者其他后端任务分布式框架中执行，这里暂时设置为同步方式执行
        result = {}
        excel_file = excel_con.sheet_by_index(0)
        nrows = excel_file.nrows  # 行
        ncols = excel_file.ncols  # 列
        if excel_file.row_values(0)[0] == '人员表':
            group_names, staff_objs = [], []
            for row in range(2, nrows):
                row_data = excel_file.row_values(row)
                group_names.append(row_data[2])
            org_objs = Organization.objects.filter(name__in=group_names)
            group_dict = {obj.name: obj.id for obj in org_objs}
            if group_dict.keys():
                not_exist_group_names = [group_name for group_name in group_names if
                                         group_name not in group_dict.keys()]
            else:
                not_exist_group_names = group_names
            if not_exist_group_names:
                result = {
                    'is_sucess': False,
                    'info': '不存在组织' + ','.join(not_exist_group_names),
                }
                return result

            for row in range(2, nrows):
                row_data = excel_file.row_values(row)
                group_names.append(row_data[2])
                staff_objs.append(Staff(
                    name=row_data[0],
                    id=row_data[1],
                    group_id=group_dict.get(row_data[2])
                ))
            Staff.objects.bulk_create(staff_objs)
            logging.debug("{model_name}: write_state: {state}".format(model_name=Staff._meta.db_table, state="Sucess!"))
            result = {
                'is_sucess': True,
                'info': '人员表存入成功',
            }
        elif excel_file.row_values(0)[0] == '组织表':
            org_objs = []
            for row in range(2, nrows):
                row_data = excel_file.row_values(row)
                org_objs.append(Organization(
                    name=row_data[0],
                    type=row_data[1],
                ))
            Organization.objects.bulk_create(org_objs)
            logging.debug("{model_name}: write_state: {state}".format(model_name=Staff._meta.db_table, state="Sucess!"))
            result = {
                'is_sucess': True,
                'info': '组织表存入成功',
            }
        else:
            result = {
                'is_sucess': False,
                'info': '不能识别表名',
            }

        return result

    def write_log(self, model_name, state):
        logging.debug("{model_name}:{state}".format(model_name=model_name, state=state))
